package com.kedacom.freedomLabel.view.fragment.setting;

import android.app.ProgressDialog;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.kedacom.freedomLabel.BR;
import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.databinding.FragmentSerialPortTestBinding;
import com.kedacom.freedomLabel.databinding.ItemSerialPortBinding;
import com.kedacom.freedomLabel.viewmodel.SerialPortViewModel;
import com.kedacom.lego.adapter.recyclerview.LegoBaseRecyclerViewAdapter;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.message.LegoMessageManager;
import com.seray.scaleviewlib.utils.Utils;
import com.skyworth.splicing.SerialPortFinder;
import com.skyworth.splicing.SerialPortUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

@ContentView(R.layout.fragment_serial_port_test)
public class SerialPortFragment extends ASettingFragment<FragmentSerialPortTestBinding, SerialPortViewModel> {

    private ArrayList<String> list = new ArrayList<>();
    private String selectSerialPort = "";
    private LegoBaseRecyclerViewAdapter<String> adapter;
    private SerialPortUtil mSerialPortUtil;
    private String[] serialCmd = {"A1", "A2", "A3", "B1", "B2", "B3"};
    private ProgressDialog pb;

    @Override
    public void saveData() {

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        selectSerialPort = PreferenceManager.getDefaultSharedPreferences(getContext()).getString("alarm_serial_port", "/dev/ttymxc3");
        list = new ArrayList<>(Arrays.asList(new SerialPortFinder().getAllDevicesPath()));
        adapter = new LegoBaseRecyclerViewAdapter<String>(R.layout.item_serial_port, list, BR.txt) {
            @Override
            protected void onCustomBindItem(ViewDataBinding binding, int position) {
                super.onCustomBindItem(binding, position);
                ((ItemSerialPortBinding) binding).text.setBackgroundColor(ContextCompat.getColor(view.getContext(),
                        list.get(position).equals(selectSerialPort) ? R.color.gray_999 : R.color.gray_ccc));
            }
        };
        mBinding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener((view1, o, i) -> {
            beep();
            selectSerialPort = adapter.getData().get(i);
            adapter.notifyDataSetChanged();
        });

        mBinding.startTest.setOnClickListener(v -> {
            beep();
            if (TextUtils.isEmpty(selectSerialPort)) {
                showToast(getString(R.string.please_select_a_serial), TOAST_ERROR);
                return;
            }
            testSerialPort();
        });

        mBinding.usePort.setOnClickListener(v -> {
            beep();
            if (TextUtils.isEmpty(selectSerialPort)) {
                showToast(getString(R.string.please_select_a_serial), TOAST_ERROR);
                return;
            }
            PreferenceManager.getDefaultSharedPreferences(getContext()).edit().putString("alarm_serial_port", selectSerialPort).apply();
            showToast("设置成功", TOAST_SUCCESS);
            LegoMessageManager.getInstance().sendMessage("CommunicationSettingFragment_updateAlarmPort", selectSerialPort);
        });
    }

    // 测试串口
    private void testSerialPort() {
        // 打开串口
        try {
            mSerialPortUtil = new SerialPortUtil(selectSerialPort, 9600);
        } catch (IOException e) {
            showToast("串口打开失败", TOAST_ERROR);
            return;
        }

        pb = new ProgressDialog(getContext());
        pb.setMessage("请稍后。。。");
        pb.setCancelable(false);
        pb.setCanceledOnTouchOutside(false);
        pb.show();
        for (int cmdIndex = 0; cmdIndex < serialCmd.length; cmdIndex++) {
            handler.postDelayed(new CmdRunnable(serialCmd[cmdIndex]), (cmdIndex * 1000));
        }

    }

    private Handler handler = new Handler();

    class CmdRunnable implements Runnable {
        private final String cmd;

        CmdRunnable(String cmd) {
            this.cmd = cmd;
        }

        @Override
        public void run() {
            if (mSerialPortUtil != null)
                mSerialPortUtil.sendBuffer(SerialPortUtil.hexString2Bytes(cmd));
            if (serialCmd[serialCmd.length - 1].equals(cmd)) {
                pb.dismiss();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mSerialPortUtil != null) mSerialPortUtil.closeSerialPort();
    }

    @Override
    public String getFragmentTitle() {
        return Utils.getApp().getString(R.string.serial_port_select);
    }
}
